#!/bin/bash
# scripts/build-and-push.sh

set -e

# 配置变量
REGISTRY_URL="localhost:5000"
IMAGE_NAME="gd-data-platform"
VERSION=${1:-$(date +%Y%m%d_%H%M%S)}
FULL_IMAGE_NAME="${REGISTRY_URL}/${IMAGE_NAME}:${VERSION}"

echo "开始构建和推送 Docker 镜像..."
echo "镜像名称: ${FULL_IMAGE_NAME}"

# 检查 Docker 是否运行
if ! docker info > /dev/null 2>&1; then
    echo "错误: Docker 未运行"
    exit 1
fi

# 登录到私有仓库
echo "登录到私有仓库..."
docker login ${REGISTRY_URL} -u admin -p admin123

# 构建应用
echo "构建 Spring Boot 应用..."
mvn clean package -DskipTests

# 构建 Docker 镜像
echo "构建 Docker 镜像..."
docker build -t ${FULL_IMAGE_NAME} .

# 推送镜像到私有仓库
echo "推送镜像到私有仓库..."
docker push ${FULL_IMAGE_NAME}

# 创建 latest 标签
echo "创建 latest 标签..."
docker tag ${FULL_IMAGE_NAME} ${REGISTRY_URL}/${IMAGE_NAME}:latest
docker push ${REGISTRY_URL}/${IMAGE_NAME}:latest

echo "构建和推送完成！"
echo "镜像地址: ${FULL_IMAGE_NAME}"
echo "Latest 镜像: ${REGISTRY_URL}/${IMAGE_NAME}:latest"
